﻿using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using System.IO;
using System.DrawingCore.Imaging;
using Common.Unit;

namespace Web.Controllers
{
    public class LoginController : BaseController
    {
        public IActionResult Index()
        {
            return View();
        }


        /// <summary>
        /// 账号密码登录
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult CheckLogin(string username, string password, string code)
        {
            try
            {
                //判断账号，密码，验证码不能为空
                Dictionary<string, string> data = new Dictionary<string, string>();
                data.Add("url", "/");
                if (string.IsNullOrEmpty(username)) throw new Exception("请输入账号!");
                if (string.IsNullOrEmpty(password)) throw new Exception("请输入密码!");
                if (string.IsNullOrEmpty(code)) throw new Exception("请输入验证码!");
                //继续验证手机号的格式和密码的格式

                //统一转化为大写比较
                if (CurrentUserCode.ToUpper() != code.ToUpper()) throw new Exception("输入验证码不正确!");

                //确认输入的字符之后，链接数据库，查询是否一致
                var checkModel = GD.BLL.GDAdmin_Bll.Instance.GetModel("mobile=@mobile",
                      new System.Data.SqlClient.SqlParameter("@mobile", username),
                      new System.Data.SqlClient.SqlParameter("@password", password));

                if (checkModel == null) throw new Exception("手机号或密码错误!");

                //if (checkModel == null || checkModel.Password != Common.Security.Secure.MD5_32(password + u.PswdSeed)) throw new Exception("用户不存在或密码错误！");
                if (checkModel.State == 2) throw new Exception("您的账号未验证,请联系网站管理员！");
                if (checkModel.State == 1) throw new Exception("您的帐号已被保护锁定，请联系网站！");

                CurrentLoginedUser = checkModel;
                data["url"] = "/home/index";
                return ajaxMsg(true, "登录成功", null, data);
            }
            catch (Exception ex)
            {
                return ajaxMsg(false, ex.Message);
            }
        }


        /// <summary>
        /// 混合验证码
        /// </summary>
        /// <returns></returns>
        public FileContentResult MixVerifyCode()
        {
            string code = BilderCode.GetSingleObj().CreateVerifyCode(BilderCode.VerifyCodeType.MixVerifyCode);
            CurrentUserCode = code;
            var bitmap = BilderCode.GetSingleObj().CreateBitmapByImgVerifyCode(code, 100, 40);
            MemoryStream stream = new MemoryStream();
            bitmap.Save(stream, ImageFormat.Gif);
            return File(stream.ToArray(), "image/gif");
        }

    }
}